﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;

namespace Axe.Collections
{
    public class StringPair: IEquatable<StringPair>
    {
        string m_Left;
        string m_Right;

        public string Left
        {
            get { return m_Left; }
            set { m_Left = value; }
        }

        public string Right
        {
            get { return m_Right; }
            set { m_Right = value; }
        }

        public StringPair()
        {
        }

        public StringPair(string left, string right)
        {
            Left = left;
            Right = right;
        }

        public override bool Equals(object obj)
        {
            if (obj is string)
                return this.Equals(obj as string);

            return base.Equals(obj);
        }

        public override int GetHashCode()
        {
            return (m_Left != null ? m_Left.GetHashCode() : 0xFFFFFF)
                ^ (m_Right != null ? m_Right.GetHashCode() : 0xFFFFFF);
        }

        #region IEquatable<StringPair> Members

        public virtual bool Equals(StringPair other)
        {
            if (other == null)
                return false;

            return Left.Equals(other.Left) && Right.Equals(other.Right);
        }

        #endregion
    }

    public class StringPairCollection : Collection<StringPair>
    {
        public StringPairCollection()
        {
        }

        public IEnumerable<string> KeysToValues(IEnumerable<string> keys)
        {
            foreach (string key in keys)
            {
                StringPair pair = GetByKey(key);
                if (pair == null)
                    throw new KeyNotFoundException(String.Format("Key {0} was not found in collection",key));

                yield return pair.Right;
            }
        }

        public StringPair GetByKey(string key)
        {
            for (int i = 0; i < Count; i++)
            {
                StringPair pair = this[i];
                if (String.Equals(pair.Left, key))
                    return pair;
            }

            return null;
        }

        #region public IEnumerable<string> Values
        public IEnumerable<string> Values
        {
            get
            {
                foreach (StringPair item in this)
                    yield return item.Right;
            }
        }
        #endregion

        #region public IEnumerable<string> Keys
        public IEnumerable<string> Keys
        {
            get
            {
                foreach (StringPair item in this)
                    yield return item.Left;
            }
        }
        #endregion
    }
}
